<template>
  <el-dialog
    title="拍照"
    :close-on-click-modal="false"
    :visible.sync="visible"
    width="1000px"
    append-to-body
  >
    <div style="text-align:right">
      <el-button v-if="videoIsOpen" size="small" @click="setImage">拍照</el-button>
      <el-upload
        style="display:inline-block;margin-left:10px"
        action="/"
        :http-request="uploadImgFile"
        multiple
        :show-file-list="false"
      >
        <el-button size="small" type="primary">选择文件</el-button>
      </el-upload>

      <!-- <el-button size="small" @click="stopNavigator">关闭摄像头</el-button> -->
      <!-- <el-button size="small">删除</el-button> -->
    </div>
    <!-- 拍摄部分 -->
    <div class="takeArea">
      <el-button v-if="!videoIsOpen" class="openCamer" @click="getCompetence">打开摄像头</el-button>
      <video id="videoCamera" :width="videoWidth" :height="videoHeight" autoplay></video>

      <div style="flex:1">
        <viewer class="preview" :images="imglist">
          <div class="preimg" v-for="(item,index) in imglist" :key="index">
            <img :src="item" alt />
            <i @click="removeImg(index)" class="el-icon-close"></i>
          </div>
          <span class="preimg"></span>
        </viewer>
      </div>
    </div>
    <canvas style="display:none;" id="canvasCamera" :width="videoWidth" :height="videoHeight"></canvas>
    <!-- 裁剪上传 -->
    <div class="clipArea" v-if="showClip">
      <div class="img-clip"></div>
      <div class="operaBox">
        <el-button size="small" @click="showClip=false">取消</el-button>
        <el-button size="small" @click="cropRotate(false)">逆时针旋转</el-button>
        <el-button size="small" @click="cropRotate(true)">顺时针旋转</el-button>
        <el-button size="small" @click="cropRect()">最大选择</el-button>
        <el-button size="small" @click="clipCImg">确定</el-button>
      </div>
    </div>

    <!-- <img src="@/assets/img/camera_01.png" alt class="bg_r_img" /> -->
    <div v-if="imgSrc" class="img_bg_camera">
      <img :src="imgSrc" alt class="tx_img" />
      <div class="img_btn_camera">
        {{validTip}}
        <!-- <img v-if="validTip === '验证中'" src="@/assets/img/loding.svg" alt class="loding_img" /> -->
      </div>
    </div>
    <!-- <div v-else class="btn_camera">把您的脸至于圆圈中央</div> -->

    <span slot="footer" class="dialog-footer">
      <el-button @click="visible = false">取消</el-button>
      <el-button type="primary" v-if="imglist.length>0" @click="dataFormSubmit()">确定</el-button>
    </span>
  </el-dialog>
</template>
<script>
import ImageClip from "@/components/image-clip";
import EXIF from "exif-js";
import "@/components/image-clip/common.css";
var cropImage;
export default {
  data() {
    return {
      visible: false,
      dataForm: {},
      videoWidth: 600,
      videoHeight: 360,
      imgSrc: "",
      videoIsOpen: false,
      imglist: [],
      thisCancas: null,
      thisContext: null,
      thisVideo: null,
      showClip: false,
      validTip: "验证中"
    };
  },
  mounted() {
    if (!window.FileReader) {
      console.error("Your browser does not support FileReader API!");
    }
    this.fileReader = new FileReader();
  },
  computed: {},
  methods: {
    removeImg(index) {
      this.imglist.splice(index, 1);
    },
    init(id) {
      this.imglist = [];
      this.dataForm.id = id || 0;
      this.visible = true;

      //打开摄像头
    },
    dataFormSubmit() {
      this.visible = false;
      if (this.imglist.length > 0) {
        this.$emit("uploadImg", this.imglist);
      } else {
        this.$message.error("图片未上传");
      }
    },
    /*
     *@author wf_Huang
     *@Time 2019/6/5 0005 17:35
     *@function  调用权限
     *****************************************/
    getCompetence() {
      var _this = this;
      this.thisCancas = document.getElementById("canvasCamera");
      this.thisContext = this.thisCancas.getContext("2d");
      this.thisVideo = document.getElementById("videoCamera");
      // 旧版本浏览器可能根本不支持mediaDevices，我们首先设置一个空对象
      if (navigator.mediaDevices === undefined) {
        navigator.mediaDevices = {};
      }
      // 一些浏览器实现了部分mediaDevices，我们不能只分配一个对象
      // 使用getUserMedia，因为它会覆盖现有的属性。
      // 这里，如果缺少getUserMedia属性，就添加它。
      if (navigator.mediaDevices.getUserMedia === undefined) {
        navigator.mediaDevices.getUserMedia = function(constraints) {
          // 首先获取现存的getUserMedia(如果存在)
          var getUserMedia =
            navigator.webkitGetUserMedia ||
            navigator.mozGetUserMedia ||
            navigator.getUserMedia;
          // 有些浏览器不支持，会返回错误信息
          // 保持接口一致
          if (!getUserMedia) {
            return Promise.reject(
              new Error("getUserMedia is not implemented in this browser")
            );
          }
          // 否则，使用Promise将调用包装到旧的navigator.getUserMedia
          return new Promise(function(resolve, reject) {
            getUserMedia.call(navigator, constraints, resolve, reject);
          });
        };
      }
      var constraints = {
        audio: false,
        video: {
          width: this.videoWidth,
          height: this.videoHeight,
          transform: "scaleX(-1)"
        }
      };
      navigator.mediaDevices
        .getUserMedia(constraints)
        .then(function(stream) {
          // 旧的浏览器可能没有srcObject
          if ("srcObject" in _this.thisVideo) {
            _this.thisVideo.srcObject = stream;
          } else {
            // 避免在新的浏览器中使用它，因为它正在被弃用。
            _this.thisVideo.src = window.URL.createObjectURL(stream);
          }
          _this.videoIsOpen = true;
          _this.thisVideo.onloadedmetadata = function(e) {
            _this.thisVideo.play();
          };
        })
        .catch(err => {
          _this.videoIsOpen = false;
          console.log(err);
        });
    },
    uploadImgFile(options) {
      let file = options.file;
      let filename = file.name;
      if (file) {
        this.fileReader.readAsDataURL(file);
      }
      this.fileReader.onload = () => {
        let base64Str = this.fileReader.result;
        this.uploadImg(base64Str);
      };
    },
    /*
     *@author wf_Huang
     *@Time 2019/6/5 0005 17:32
     *@function  绘制图片
     *****************************************/
    setImage() {
      var _this = this;
      // 点击，canvas画图
      _this.thisContext.drawImage(
        _this.thisVideo,
        0,
        0,
        _this.videoWidth,
        _this.videoHeight
      );
      // 获取图片base64链接
      var b64 = this.thisCancas.toDataURL("image/png");

      this.loadImg(b64);
      // _this.imgSrc = image;
      // this.$emit("refreshDataList", this.imgSrc);
    },
    loadImg(b64) {
      this.showClip = true;
      var img = new Image();
      img.src = b64;
      img.onload = function() {
        EXIF.getData(img, function() {
          var orientation = EXIF.getTag(this, "Orientation");
          cropImage && cropImage.destroy();
          cropImage = new ImageClip({
            container: ".img-clip",
            img,
            // 0代表按下才显示，1恒显示，-1不显示
            sizeTipsStyle: 0,
            // 为1一般是屏幕像素x2这个宽高
            // 最终的大小为：屏幕像素*屏幕像素比（手机中一般为2）*compressScaleRatio
            compressScaleRatio: 1.1,
            // iphone中是否继续放大：x*iphoneFixedRatio
            // 最好compressScaleRatio*iphoneFixedRatio不要超过2
            iphoneFixedRatio: 1.8,
            // 减去顶部间距，底部bar,以及显示间距
            maxCssHeight: window.innerHeight - 100 - 50 - 20,
            // 放大镜捕获的图像半径
            captureRadius: 30,
            // 是否采用原图像素（不会压缩）
            isUseOriginSize: false,
            // 增加最大宽度，增加后最大不会超过这个宽度
            maxWidth: 0,
            // 是否固定框高，优先级最大，设置后其余所有系数都无用直接使用这个固定的宽，高度自适应
            forceWidth: 0,
            // 同上，但是一般不建议设置，因为很可能会改变宽高比导致拉升，特殊场景下使用
            forceHeight: 0,
            // 压缩质量
            quality: 0.92,
            mime: "image/jpeg"
          });
          console.log(orientation);
          cropImage.rotate(true);
          // 6代表图片需要顺时针修复（默认逆时针处理了，所以需要顺过来修复）
          switch (orientation) {
            case 6:
              cropImage.rotate(true);
              break;
            default:
              break;
          }
        });
      };
    },
    cropRotate(flag) {
      cropImage.rotate(flag);
    },
    cropRect() {
      cropImage.resetClipRect();
    },
    clipCImg() {
      this.$confirm(`是否裁剪图片并处理？`, "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      })
        .then(() => {
          cropImage.clip(false);
          let imgData = cropImage.getClipImgData();
          this.uploadImg(imgData);
        })
        .catch(() => {});
    },
    uploadImg(b64) {
      this.$http({
        url: this.$http.adornUrl(`/air/upload/img `),
        method: "post",
        data: this.$http.adornData({
          photo: b64.split(",")[1]
        })
      }).then(({ data }) => {
        if (data && data.result == "1") {
          this.imglist.push(data.url);
          this.$message({
            message: "操作成功",
            type: "success",
            duration: 1500,
            onClose: () => {}
          });
        } else {
          this.$message.error(data.message);
        }
      });

      this.showClip = false;
    },

    /*
     *@function  关闭摄像头
     *****************************************/
    stopNavigator() {
      this.thisVideo.srcObject.getTracks()[0].stop();
      this.videoIsOpen = false;
    }
  },

  beforeDestroy() {
    this.stopNavigator();
  }
};
</script>
<style lang="scss" scoped>
.dialogZX {
  z-index: 2006;
}
.takeArea {
  display: flex;
  padding: 20px;
  position: relative;
  .openCamer {
    position: absolute;
    left: 250px;
    top: 170px;
    z-index: 6;
  }
}
.preview {
  flex: 1;
  background-color: #bee7ff;
  padding: 10px;
  overflow: auto;
  height: 360px;
  justify-content: space-around;
  display: flex;
  flex-wrap: wrap;
  .preimg {
    width: 120px;
    height: 180px;

    margin-top: 10px;

    position: relative;
    img {
      width: 120px;
      height: 180px;
      display: block;
      background-color: #fff;
    }
    &:hover {
      .el-icon-close {
        display: block;
      }
    }
    .el-icon-close {
      position: absolute;
      right: 5px;
      top: 5px;
      font-size: 14px;
      display: none;
      color: #606266;
      cursor: pointer;
    }
  }
}
video {
  background-color: #f6f6f6;
}
.camera_outer {
  position: relative;
  overflow: hidden;
  background-size: 100%;

  video,
  canvas,
  .tx_img {
    -moz-transform: scaleX(-1);
    -webkit-transform: scaleX(-1);
    -o-transform: scaleX(-1);
    transform: scaleX(-1);
  }
  .btn_camera {
    position: absolute;
    bottom: 4px;
    left: 0;
    right: 0;
    height: 50px;
    background-color: rgba(0, 0, 0, 0.3);
    line-height: 50px;
    text-align: center;
    color: #ffffff;
  }
  .bg_r_img {
    position: absolute;
    bottom: 0;
    left: 0;
    right: 0;
    top: 0;
  }
  .img_bg_camera {
    position: absolute;
    bottom: 0;
    left: 0;
    right: 0;
    top: 0;
    img {
      width: 100%;
      height: 100%;
    }
    .img_btn_camera {
      position: absolute;
      bottom: 0;
      left: 0;
      right: 0;
      height: 50px;
      line-height: 50px;
      text-align: center;
      background-color: rgba(0, 0, 0, 0.3);
      color: #ffffff;
      .loding_img {
        width: 50px;
        height: 50px;
      }
    }
  }
}
.clipArea {
  position: fixed;
  left: 0;
  top: 0;
  bottom: 0;
  right: 0;
  background-color: #000;
  padding: 30px;
}
.operaBox {
  padding: 30px;
  text-align: center;
}
</style>